package com.ldatum.crm.daoImpl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.ldatum.crm.dao.EmployeeDao;
import com.ldatum.crm.domain.Employee;
import com.ldatum.crm.util.HibernateUtil;

public class EmployeeDaoImpl implements EmployeeDao {

	@Override
	public void add(Employee employee) throws Exception {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(employee);
			tx.commit();
		}finally{
			if(s!=null)
			s.close();
		}
	}

	@Override
	public void delete(Employee employee, int id) throws Exception {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.delete(employee);
			tx.commit();
		}finally{
			if(s!=null)
			s.close();
		}
	}

	@Override
	public void update(Employee employee, int id) throws Exception {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.update(employee);
			tx.commit();
		}finally{
			if(s!=null)
			s.close();
		}
	}

	@Override
	public Employee findById(Class<Employee> clazz,int id) throws Exception {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			return (Employee) s.get(clazz, id);
		}finally{
			if(s!=null)
			s.close();
		}
	}

	@Override
	public Employee findByLoginname(Class<Employee> clazz, String loginname)
			throws Exception {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			Criteria c  = s.createCriteria(clazz);
			c.add(Restrictions.eq("loginname", loginname));
			Employee emp = (Employee) c.uniqueResult();
			return emp;
		}finally{
			s.close();
		}
	}

	@Override
	public List<Employee> list(Class<Employee> clazz) throws Exception {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			String hql = "from Employee as employee order by fullname ASC";
			Query q = s.createQuery(hql);
			@SuppressWarnings("unchecked")
			List<Employee> list = (List<Employee>) q.list();
			return list;
		}finally{
			s.close();
		}
	}

}
